package cn.dengta.webapp.trade.entity;

import java.math.BigDecimal;

import cn.dengta.webapp.base.entity.BaseEntity;
import cn.dengta.webapp.base.entity.TimeBasedEntity;
import cn.dengta.webapp.trade.model.GoldTradeType;
import cn.dengta.webapp.trade.model.TradeTypeCore;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 用户金币操作记录
 *
 * @author Ready
 * @since 2022-11-21
 */
@Setter
@Getter
@Accessors(chain = true)
@TableName("tr_user_gold_log")
public class UserGoldLog extends TimeBasedEntity {

	private static final long serialVersionUID = 1L;

	/** 用户id */
	Long userId;
	/** 交易类型 */
	GoldTradeType tradeType;
	/** 资金流向：1=收入；0=不变；-1=支出 */
	Integer flow;
	/** 交易额度 */
	Integer tradeAmount;
	/** 本次交易后的总额度 */
	Integer totalAmount;
	/** 本次交易后的可用余额 */
	Integer activeAmount;
	/** 本次交易后的冻结金额 */
	Integer frozenAmount;
	/** 关联的业务实体类型 */
	String assocType;
	/** 关联的业务实体ID */
	Long assocId;
	/** 关联实体的数量 */
	BigDecimal assocNum;
	/** 备注 */
	String remark;

	protected transient BaseEntity assocObj;

	/** 交易初始化化 */
	public static UserGoldLog init(UserGold gold, GoldTradeType tradeType, Integer tradeAmount, BaseEntity obj) {
		TradeTypeCore core = tradeType.getFrom();
		UserGoldLog log = new UserGoldLog();
		log.setUserId(gold.getUserId());
		log.setTradeType(tradeType);
		log.setTradeAmount(core.isConsume() ? -tradeAmount : tradeAmount);
		log.setFlow(core.getFlow().value);
		gold.calc(core, tradeAmount);
		log.totalAmount = gold.getTotalAmount();
		log.activeAmount = gold.getActiveAmount();
		log.frozenAmount = gold.getFrozenAmount();
		log.handleAssocObject(obj);
		return log;
	}

	public void handleAssocObject(BaseEntity obj) {
		if (obj != null) {
			this.assocObj = obj;
			this.assocType = obj.entityName();
			this.assocId = obj.getId();
		}
	}

	public static final String USER_ID = "user_id";
	public static final String TRADE_TYPE = "trade_type";
	public static final String FLOW = "flow";
	public static final String TRADE_AMOUNT = "trade_amount";
	public static final String TOTAL_AMOUNT = "total_amount";
	public static final String ACTIVE_AMOUNT = "active_amount";
	public static final String FROZEN_AMOUNT = "frozen_amount";
	public static final String ASSOC_TYPE = "assoc_type";
	public static final String ASSOC_ID = "assoc_id";
	public static final String REMARK = "remark";

}
